package project6.voip;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.util.Log;

public class VoicePlayerServer extends Thread 
{
	private static final String TAG = "VPS";
	static public DatagramSocket socket;
	int port;
	private AudioTrack speaker;
	private int sampleRate = 8000;
	private int cConfig = AudioFormat.CHANNEL_CONFIGURATION_MONO;
	private int aFormat = AudioFormat.ENCODING_PCM_16BIT;
	public Activity activity;
	private boolean close;
	VoicePlayerServer(Activity activity, int port) throws UnknownHostException, SocketException 
	{
		super();
		close = false;
		this.port = port;
		socket = new DatagramSocket(port);
		this.activity = activity;
	}
	
	public void run() 
	{
		android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
		byte[][] buffers = new byte[256][160];
		int k = 0;
		int minBuf = AudioTrack.getMinBufferSize(sampleRate,cConfig,aFormat);
		byte[] buffer = null;
		DatagramPacket packet = null;
		speaker = new AudioTrack(AudioManager.STREAM_VOICE_CALL,sampleRate,cConfig,aFormat,minBuf,AudioTrack.MODE_STREAM);
		speaker.play();
		
		while(!close) 
		{
			try 
			{
				buffer = buffers[k++ % buffers.length];
				packet = new DatagramPacket(buffer, buffer.length);
				//System.out.println("pre receive packet on port: " + port);
				socket.receive(packet);
				//System.out.println("received packet");
				buffer=packet.getData();
				//System.out.println("pre write to speaker");
				speaker.write(buffer,0,buffer.length);
				//Log.i(TAG,"speaker write");			
			} 
			catch (IOException e) 
			{
				Log.e(TAG, "Error: "+ e);
			}
		}
		System.out.println("threads going to stop");
	}
	public void close() 
	{
		if(speaker != null) 
		{
			speaker.release();
		}
		close=true;
	}
}
